package com.begye.smartloan.apptest.certify.adapter

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.begye.smartloan.apptest.R
import org.json.JSONObject

class CertifySelfieImageAdapter(var dataList: List<JSONObject>, val onClickAction: (Int, Int) -> Unit) :
    RecyclerView.Adapter<CertifySelfieImageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item_certify_selfie_image, parent, false)

//        val screenWidth = parent.context.screenWidth()
//        val edgeWidth = parent.context.dpToPx(56F).toInt()
//        val itemWidth = (screenWidth - edgeWidth) / 3
//        val layoutParams = view.layoutParams
//        layoutParams.width = itemWidth
//        layoutParams.height = itemWidth
//        view.layoutParams = layoutParams

        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val listItemCertifySelfieImageContent: RelativeLayout =
            view.findViewById(R.id.listItemCertifySelfieImageContent)

        private val listItemCertifySelfieImage: ImageView =
            view.findViewById(R.id.listItemCertifySelfieImage)

        private val listItemCertifySelfieDelete: ImageView =
            view.findViewById(R.id.listItemCertifySelfieDelete)


        @SuppressLint("SetTextI18n")
        fun bindData(position: Int, item: JSONObject) {

            val isAdd = item.optString("isAdd", "NO")
            val filePath = item.optString("path", "")

            if (filePath.isNotBlank()) {
                try {
                    val options = BitmapFactory.Options().apply {
                        inJustDecodeBounds = false
                    }
                    val bitmap = BitmapFactory.decodeFile(filePath, options)
                    listItemCertifySelfieImage.setImageBitmap(bitmap)

                } catch (e: Exception) {
                    //
                }
            }

            listItemCertifySelfieDelete.setOnClickListener {
                onClickAction.invoke(1, position)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindData(position, dataList[position])
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}